import datetime

from django.contrib.auth import authenticate
from django.utils import timezone
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

from user.models import ImageVerifyCode


class UserSerializer(ModelSerializer):
    uuid = serializers.UUIDField(write_only=True)
    verify = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = '__all__'

    def validate(self, attrs):
        uuid = attrs.get('uuid')
        verify = attrs.get('verify')
        # 查询答案
        try:
            code_record = ImageVerifyCode.objects.get(uuid=uuid)
            five_minutes_ago = timezone.now() - datetime.timedelta(minutes=5)
            if code_record.create_at < five_minutes_ago:
                code_record.delete()
                raise serializers.ValidationError('验证码过期')
            if code_record.code.upper() != verify.upper():
                code_record.delete()
                raise serializers.ValidationError("验证码错误")
            code_record.delete()
        except ImageVerifyCode.DoesNotExist:
            raise serializers.ValidationError("验证码过期")

        return attrs


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    uuid = serializers.UUIDField(write_only=True)
    verify = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = '__all__'

    def validate(self, attrs):
        uuid = attrs.get('uuid')
        verify = attrs.get('verify')
        username = attrs.get('username')
        password = attrs.get('password')
        # 查询答案
        print(attrs)
        try:
            code_record = ImageVerifyCode.objects.get(uuid=uuid)
            five_minutes_ago = timezone.now() - datetime.timedelta(minutes=5)

            if code_record.create_at < five_minutes_ago:
                code_record.delete()
                raise serializers.ValidationError('验证码过期')
            if code_record.code.upper() != verify.upper():
                code_record.delete()
                raise serializers.ValidationError("验证码错误")
            user = authenticate(username=username, password=password)
            if user is None:
                raise serializers.ValidationError("账号或者密码错误")
            refresh = self.get_token(user)
            code_record.delete()
        except ImageVerifyCode.DoesNotExist:
            raise serializers.ValidationError("验证码过期")

        return {'user': user.get_username(), 'token': str(refresh.access_token)}
